import 'package:flutter/material.dart';
import 'package:kasax_demos2/providers/page_providers.dart';
import 'package:provider/provider.dart';

import 'page_provider_list.dart';

/// Flutter中使用Provider底部导航进行状态管理
/// https://www.jianshu.com/p/e1f9e026991e
class ProviderForBottomNavigationBarDemoHome extends StatefulWidget {
  const ProviderForBottomNavigationBarDemoHome({Key? key}) : super(key: key);

  @override
  _ProviderForBottomNavigationBarDemoHomeState createState() =>
      _ProviderForBottomNavigationBarDemoHomeState();
}

class _ProviderForBottomNavigationBarDemoHomeState
    extends State<ProviderForBottomNavigationBarDemoHome> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ChangeNotifierProvider<BottomNavigationBarProvider>(
        child: BottomNavigationBarExample(),
        create: (_) => BottomNavigationBarProvider(),
      ),
    );
  }
}

class BottomNavigationBarExample extends StatelessWidget {
  const BottomNavigationBarExample({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var bottomNavProvider = Provider.of<BottomNavigationBarProvider>(context);
    var currentTab = [
      PageProviderUI("home"),
      PageProviderUI("profile"),
      PageProviderUI("settings")
    ];
    return Scaffold(
      appBar: AppBar(
        title: Text("底部导航管理"),
        centerTitle: true,
      ),
      // body: currentTab[bottomNavProvider.currentIndex],
      body: Consumer<BottomNavigationBarProvider>(
        builder: (context, provider, child) {
          return currentTab[provider._currentIndex];
        },
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: bottomNavProvider.currentIndex,
        onTap: (index) {
          bottomNavProvider.updateIndex(index);
        },
        items: [
          BottomNavigationBarItem(icon: Icon(Icons.home), title: Text("Home")),
          BottomNavigationBarItem(
              icon: Icon(Icons.person), title: Text("Profile")),
          BottomNavigationBarItem(
              icon: Icon(Icons.settings), title: Text("Settings")),
        ],
      ),
    );
  }
}

/// BottomNavigationBarProvider 是ChangeNotifier的扩展类，用于调用notifyListener()方法后进行广播
class BottomNavigationBarProvider extends ChangeNotifier {
  int _currentIndex = 0;

  get currentIndex => _currentIndex;

  updateIndex(int index) {
    _currentIndex = index;
    notifyListeners();
  }
}
